import random
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection


from apps.verifications import constants
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request,uuid):
        #生成图片验证码
        text, image = captcha.generate_captcha()
        #链接redis
        redis_conn = get_redis_connection('code')
        #设置有效期
        redis_conn.setex('img_%s'%uuid,constants.IMAGE_CODE_REDIS_EXPIRES, text)

        #返回响应信息
        return http.HttpResponse(image, content_type='image/jpeg')

class SmsCodeView(View):
    def get(self,request,mobile):
        uuid = request.GET.get('image_code_id')
        image_code_client = request.GET.get('image_code')
        if not all([uuid, image_code_client]):
            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR,'errmsg':'参数不全'})
        #创建redis链接
        conn = get_redis_connection('code')
        # 获取redis数据库中图形验证码
        image_code_server = conn.get('img_%s'%uuid)
        if image_code_server is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图片验证码错误'})
        #删除图像验证码，避免恶意测试图形验证码
        try:
            conn.delete('img_%s'%uuid)
        except Exception as e:
            logger.error(e)

        #验证用户输入的图片验证码和redis数据库中的图形验证码是否一致
        #将二进制转化成字符串
        image_code_server = image_code_server.decode()
        send_flag = conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR, 'errmsg':'发送短信信息过于频繁'})


        if image_code_server.lower() != image_code_client.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'验证码输入有误，请重新输入'})
        #生成短信验证码:生成６位数验证码
        sms_code = '%06d' % random.randint(0, 9999)
        #将短信验证码存放在redis ２号数据库中
        conn.setex('sms_%s'%mobile, constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        #在redis数据库中添加标记位，避免短信重复
        conn.setex('send_flag_%s'%mobile, constants.SEND_FLAGE_EXPIRES,1)
        #发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SEND_SMS_TEMPLATE_ID)
        #调用队列中短信验证码的任务
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'短信发送成功'})




